# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:49
# File     : manager.py
# Project  : codebuddy_craft
# Desc     :
# backend/database/manager.py
"""
数据库管理工具 🛠️

提供数据库管理命令行工具
"""

import asyncio
import click
from pathlib import Path
from datetime import datetime

from backend.database.connection import (
    init_db, reset_database, backup_database,
    get_database_stats, health_check, close_db_connections
)
from backend.core.settings import get_settings

settings = get_settings()


@click.group()
def db():
    """数据库管理命令 🗄️"""
    pass


@db.command()
def init():
    """初始化数据库 🚀"""
    click.echo("🔧 正在初始化数据库...")
    asyncio.run(init_db())
    click.echo("✅ 数据库初始化完成")


@db.command()
def reset():
    """重置数据库 ⚠️"""
    if not settings.is_development:
        click.echo("❌ 只能在开发环境重置数据库")
        return

    if click.confirm("⚠️ 这将删除所有数据！确定要重置数据库吗？"):
        click.echo("🔄 正在重置数据库...")
        asyncio.run(reset_database())
        click.echo("✅ 数据库重置完成")
    else:
        click.echo("❌ 操作已取消")


@db.command()
@click.option("--path", default=None, help="备份文件路径")
def backup(path):
    """备份数据库 💾"""
    if not path:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        path = f"backups/db_backup_{timestamp}.db"

    click.echo(f"💾 正在备份数据库到: {path}")

    async def run_backup():
        success = await backup_database(path)
        if success:
            click.echo("✅ 数据库备份完成")
        else:
            click.echo("❌ 数据库备份失败")

    asyncio.run(run_backup())


@db.command()
def stats():
    """显示数据库统计信息 📊"""
    click.echo("📊 获取数据库统计信息...")

    async def run_stats():
        stats = await get_database_stats()
        click.echo("\n📈 数据库统计信息:")
        click.echo(f"用户数量: {stats['users']}")
        click.echo(f"项目数量: {stats['projects']}")
        click.echo(f"文件数量: {stats['files']}")
        click.echo(f"总代码行数: {stats['total_lines']:,}")
        click.echo(f"数据库大小: {stats['database_size']}")

    asyncio.run(run_stats())


@db.command()
def health():
    """检查数据库健康状态 🏥"""
    click.echo("🏥 检查数据库健康状态...")

    async def run_health():
        result = await health_check()

        if result["status"] == "healthy":
            click.echo("✅ 数据库状态健康")
            click.echo(f"响应时间: {result['response_time_ms']}ms")
            if result.get('pool_size') != 'N/A':
                click.echo(f"连接池大小: {result['pool_size']}")
                click.echo(f"已签出连接: {result['checked_out']}")
        else:
            click.echo("❌ 数据库状态异常")
            click.echo(f"错误: {result.get('error', '未知错误')}")

    asyncio.run(run_health())


if __name__ == "__main__":
    db()
